package com.gnerv.sylvanas.business.manage.logic;

import com.gnerv.sylvanas.framework.common.model.RestResult;
import com.gnerv.sylvanas.framework.core.BaseUkIdGenerate;
import com.gnerv.sylvanas.business.manage.model.bo.PostBO;
import com.gnerv.sylvanas.business.manage.model.dto.PostCreateDTO;
import com.gnerv.sylvanas.business.manage.model.dto.PostDTO;
import com.gnerv.sylvanas.business.manage.model.dto.PostUpdateDTO;
import com.gnerv.sylvanas.business.manage.operation.PostOperationService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Gnerv LiGen
 */
@Slf4j
@Service
@AllArgsConstructor
public class PostLogicService  {

    private final PostOperationService postOperationService;
    private final BaseUkIdGenerate baseUkIdGenerate;

    
    @Transactional(rollbackFor = {Exception.class})
    public RestResult<Void> create(PostCreateDTO postCreateDTO) {
        PostBO postBO = postCreateDTO.toPostBO();
        postBO.setUkId(baseUkIdGenerate.generate());
        postOperationService.create(postBO);
        postOperationService.bindOrg(postBO.getUkId(), postCreateDTO.getOrgUkId());
        return RestResult.ok();
    }

    
    @Transactional(rollbackFor = {Exception.class})
    public RestResult<Void> deleteByUkId(String ukId) {
        postOperationService.deleteByUkId(ukId);
        return RestResult.ok();
    }

    
    @Transactional(rollbackFor = {Exception.class})
    public RestResult<Void> updateByUkId(PostUpdateDTO postUpdateDTO) {
        PostBO postBO = postUpdateDTO.toPostBO();
        postOperationService.updateByUkId(postBO);
        postOperationService.unbindOrg(postBO.getUkId());
        postOperationService.bindOrg(postBO.getUkId(), postUpdateDTO.getOrgUkId());
        return RestResult.ok();
    }

    
    @Transactional(readOnly = true)
    public RestResult<PostDTO> selectByUkId(String ukId) {
        PostDTO postDTO = postOperationService.selectByUkId(ukId);
        return RestResult.ok(postDTO);
    }

    
    public RestResult<PostDTO> selectByName(String name) {
        PostDTO postDTO = postOperationService.selectByName(name);
        return RestResult.ok(postDTO);
    }

    
    @Transactional(readOnly = true)
    public RestResult<List<PostDTO>> selectListByName(String name) {
        return RestResult.ok(postOperationService.selectListByName(name));
    }

}
